<?php
namespace app\servercertificate\logic;
use \app\manage\logic\BaseLogic;
use \think\Db;
/**
 * @author:      李颖
 * @DateTime:    2017-06-15 09:56:20
 * @Description: 证书
 */
class Certificate extends BaseLogic
{
	protected $name = 'certificate';
    protected $config = 'db_config_certificate';
    protected $certificateModel = 'app\servercertificate\model\Certificate';
    protected $pickUpGoodsModel = 'app\servercertificate\model\Pickupgoods';
    protected $certificateIntegralDistributeModel = 'app\servercertificate\model\CertificateIntegralDistribute';
    /*这里的搜索值若为0，则不参与搜索,故status采用数组形式 $_where['status'] = ['in',[0]]*/
    protected $searchOneWhere = ['id'=>'eq','user_id'=>'eq','goods_id'=>'eq','status'=>'in'];

    /*生成普通证书*/
    public function applyCertificate($data): array 
    {

        $data['type'] = 'common';
        $data['name'] = $data['goods_info']['title'] . '证书';
        $data['app_id'] = $data['goods_info']['app_id'];
        $data['other_app_read'] = $data['goods_info']['other_app_read'];
        $data['is_public'] = $data['goods_info']['is_public'];
        try{
            $res = $this->model($this->certificateModel)->save($data);
        }catch(\Exception $e){
            return server_err(null, '数据库错误' . $e->getMessage() );
        }
        $res && $res = $this->model($this->certificateModel)->id;

        return auto_return($res);
    }

    /*生成高级证书*/
    public function applyAdvancedCertificate($data): array 
    {
        $saveList = [];
        $i = 0;

        // 处理证书表里存的订单信息
        $orderInfo = $data['order_info'];
        $orderInfo['goods_infos'] = $this->_dealGoodsInfos($orderInfo['goods_infos']);

        foreach ($data['order_info']['goods_infos'] as $k => $v) {
            for($j = 0; $j < $v['order_number']; $j++){
                //添加一条证书记录
                $saveData['order_user_id'] = $data['user_id'];
                $saveData['certificate_price'] = $data['pay_method'] == 'currency' ? $v['final_currency_price'] : $v['final_price'];
                $saveData['pay_method'] = $data['pay_method'];
                $saveData['app_id'] = $v['app_id'];
                $saveData['other_app_read'] = $v['other_app_read'];
                $saveData['is_public'] = $v['is_public'];
                $saveData['name'] = $v['title'] . '证书';
                $saveData['product_code'] = $data['product_code'][$i];   
                $saveData['user_id'] = $data['user_id'];
                $saveData['goods_id'] = $v['id'];
                // 简化证书表里的商品信息
                $saveData['goods_info'] = $this->_simpleGoodsInfo($v);
                $saveData['order_info'] = $orderInfo;
                $saveData['transfer_log'] = [];
                $saveData['type'] = 'advanced';
                $saveData['earnings'] = 0;
                $saveData['is_transfer'] = 0;
                $saveData['is_pick'] = 0;
                $saveData['is_recommend'] = 0;
                $saveData['apply_invalid'] = 0;
                $saveData['is_transfer'] = 0;
                $saveData['status'] = 1;  //审核通过状态
                $saveData['finish_distribute_time'] = bcadd(bcmul($v['pick_up_time'], 86400), $data['order_info']['pay_time']);
                $saveData['pay_time'] = $data['order_info']['pay_time'];
                $saveData['goods_cate_ids'] = $v['search_fields']['cate_ids'];
                // $saveData['sell_price'] = $saveData['certificate_price'];
                $saveData['sell_price'] = 0;
                $saveList[] = $saveData;
                $i++;
            }
        }
        try{
            $res = $this->model($this->certificateModel)->saveAll($saveList);
        }catch(\Exception $e){
            return server_err(null, '数据库错误' . $e->getMessage() );
        }
        return auto_return($res);
    }
    // 简化订单信息里的商品信息
    protected function _dealGoodsInfos($goodsInfos): array 
    {
        $newGoodsInfos = [];
        foreach ($goodsInfos as $k => $v) {
            $newV['id'] = $v['id'];
            $newV['price'] = $v['price'];
            $newV['title'] = $v['title'];
            $newV['number'] = $v['number'];
            $newV['final_price'] = $v['final_price'];
            $newV['order_number'] = $v['order_number'];
            $newV['pick_up_time'] = $v['pick_up_time'];
            $newV['final_total_price'] = $v['final_total_price'];
            $newV['goods_belonger_name'] = $v['goods_belonger_name'];
            $newV['start_delivery_time'] = $v['start_delivery_time'];
            $newV['final_currency_price'] = $v['final_currency_price'];
            $newV['final_total_currency_price'] = $v['final_total_currency_price'];
            $newGoodsInfos[$k] = $newV;
        }
        return $newGoodsInfos;
    }
    // 简化证书表里的商品信息
    protected function _simpleGoodsInfo($goodsInfo): array 
    {
        $newGoodsInfo = [];
        $newGoodsInfo['id'] = $goodsInfo['id'];
        $newGoodsInfo['price'] = $goodsInfo['price'];
        $newGoodsInfo['title'] = $goodsInfo['title'];
        $newGoodsInfo['choose'] = $goodsInfo['choose'];
        $newGoodsInfo['authors'] = $goodsInfo['authors'];
        $newGoodsInfo['cate_name'] = $goodsInfo['cate_name'];
        $newGoodsInfo['user_id'] = $goodsInfo['user_id'];
        $newGoodsInfo['img_desc'] = $goodsInfo['img_desc'];
        $newGoodsInfo['imgs_urls'] = $goodsInfo['imgs_urls'];
        $newGoodsInfo['text_desc'] = $goodsInfo['text_desc'];
        $newGoodsInfo['desc'] = $goodsInfo['desc'];
        $newGoodsInfo['pay_method'] = $goodsInfo['pay_method'];
        $newGoodsInfo['final_price'] = $goodsInfo['final_price'];
        $newGoodsInfo['profile_pic'] = $goodsInfo['profile_pic'];
        $newGoodsInfo['organization'] = $goodsInfo['organization'];
        $newGoodsInfo['pick_up_time'] = $goodsInfo['pick_up_time'];
        $newGoodsInfo['product_code'] = $goodsInfo['product_code'];
        $newGoodsInfo['end_delivery_time'] = $goodsInfo['end_delivery_time'];
        $newGoodsInfo['final_total_price'] = $goodsInfo['final_total_price'];
        $newGoodsInfo['latest_refund_time'] = $goodsInfo['latest_refund_time'];
        $newGoodsInfo['goods_belonger_name'] = $goodsInfo['goods_belonger_name'];
        $newGoodsInfo['start_delivery_time'] = $goodsInfo['start_delivery_time'];
        $newGoodsInfo['final_currency_price'] = $goodsInfo['final_currency_price'];
        $newGoodsInfo['final_total_currency_price'] = $goodsInfo['final_total_currency_price'];
        $newGoodsInfo['orther_info'] = $goodsInfo['orther_info'];
        $newGoodsInfo['search_fields'] = $goodsInfo['search_fields'];
        $newGoodsAttrs = [];
        foreach ($goodsInfo['goods_attrs'] as $k => &$v) {
            $v2['name'] = $v['name'];
            $v2['value'] = $v['value'];
            $v2['is_show'] = $v['is_show'];
            $newGoodsAttrs[$k] = $v2;
        }
        $newGoodsInfo['goods_attrs'] = $newGoodsAttrs;
        return $newGoodsInfo;
    }

    /*简单的获取证书信息*/
    public function getSimpleCertiInfo($data): array 
    {
        $res = $this->dbCertifiInfo($data);
        return auto_return($res, '成功查询该证书信息', '未找到该证书信息');
    }
    /*查询证书详情*/
    public function dbCertifiInfo($data)
    {
        $_where = $this->searchWhere($data, $this->searchOneWhere);
        //return $this->db()->where($_where)->find();
        return $this->model($this->certificateModel)->field('goods_info,order_info,transfer_log', true)->where($_where)->find();
    } 

    /*管理员将某一证书作废*/
    public function invalid($data): array 
    {
        $_where['id'] = $data['id'];
        $saveData['status'] = 3;
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res);
    }

    /*用户申请作废某一证书*/
    public function applyInvalid($data): array
    {
        $_where['id'] = $data['id'];
        $_where['user_id'] = $data['user_id'];
        $_where['type'] = 'common';
        $_where['apply_invalid'] = 0;
        $_where['status'] = ['in','0,1,2'];
        $saveData['apply_invalid'] = 1;
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res, '申请成功', '申请失败');
    }
    
    /*根据不同条件 获取某一证书详情 获取任何字段值*/
    public function certificateInfo($data): array 
    {
        $_where['c.id'] = $data['id'];
        if(isset($data['goods_id']) && $data['goods_id']){ $_where['c.goods_id'] = $data['goods_id']; }
        if(isset($data['user_id']) && $data['user_id']){ $_where['c.user_id'] = $data['user_id']; }
        if(isset($data['status']) && $data['status']){ $_where['c.status'] = ['in', $data['status']]; }
        $res = $this->model($this->certificateModel)
                    ->alias('c')
                    ->field('c.*,p.pick_up_code, p.order_type, p.name as pick_up_name, p.phone as pick_up_phone, p.address as pick_up_address, p.logistics_company_code, p.logistics_company_name, p.waybill_number, p.transfer_status, p.shipments_time, p.pick_up_time')
                    ->join('pick_up_goods p', 'p.certificate_id = c.id', 'LEFT')
                    ->order('c.id DESC')
                    ->where($_where)
                    ->find();
        //添加收益记录
        $res['earningsList'] = $this->_getIntegralDistributeList($data);
        return auto_return($res, '成功获取证书详情', '获取证书详情失败');
    }

    /*获取我的某一证书详情  包括我待处理的证书 我转让过的证书*/
    public function myCertificateInfo($data): array 
    {
        $_where['c.id'] = $data['id'];
        $_whereOr = 'c.user_id = ' . $data['user_id'] . ' OR t.user_id = ' . $data['user_id'] . ' OR t.to_user = ' . $data['user_id'];
        $res = $this->model($this->certificateModel)
                    ->alias('c')
                    ->field('c.*, p.pick_up_code, p.transfer_status')
                    ->join('pick_up_goods p', 'p.certificate_id = c.id', 'LEFT')
                    ->join('transfer_log t', 't.certificate_id = c.id', 'LEFT')
                    ->where($_where)
                    ->where($_whereOr)
                    ->find();
        $res && $res['earningsList'] = $this->_getIntegralDistributeList($data);
        return auto_return($res, '成功获取证书详情', '获取证书详情失败');
    }

    protected function _getIntegralDistributeList($data): array 
    {
        $_findDistribute['certificate_id'] = $data['id'];
        $_findDistribute['status'] = 1;
        return $this->model($this->certificateIntegralDistributeModel)->order('distribute_date_time asc,id desc')->where($_findDistribute)->select();
    }

    /*修改证书编号*/
    public function updateProductCode($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $saveData['product_code'] = $data['product_code'];
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res, '成功修改证书编号', '修改证书编号失败');
    }

    /*管理员审核某一证书*/
    public function auditOneCertificate($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 0;
        $saveData['status'] = $data['status'];
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res);
    }

    /*对方同意或拒绝证书转让时  修改证书持有人信息等 $data: 转让记录表里的一条记录*/
    public function transferCertificate($data, bool $isAgree): array 
    {

        $_where['status'] = 1;
        $_where['is_transfer'] = 1;
        $_where['id'] = $data['certificate_id'];
        $_where['user_id'] = $data['user_id'];
        $info = $this->model($this->certificateModel)->field('goods_info,order_info', true)->where($_where)->find();
        if(!$info){ return auto_failure(null, '未找到符合条件的证书信息'); }
        $info = $info->toArray();

        // 对data进行简化用户的信息
        $newTransLog = [];
        $newTransLog['user_id'] = $data['user_id'];
        $newTransLog['to_user'] = $data['to_user'];
        $newTransLog['status'] = $data['status'];
        $newTransLog['status_text'] = $data['status_text'];
        $newTransLog['create_time'] = $data['create_time'];
        $newTransLog['update_time'] = $data['update_time'];
        $newTransLog['user_info'] = ['name'=>$data['user_info']['name']];
        $newTransLog['to_user_info'] = ['name'=>$data['to_user_info']['name']];

        if(!$info['transfer_log']){
            $transfers = [];
            $transfers[] = $newTransLog;
        }else{
            array_push($info['transfer_log'], $newTransLog);  //将转让记录表的一条记录压到证书表里的转让记录字段中
            $transfers = $info['transfer_log'];
        }
      
        $saveData['is_transfer'] = 0;
        //$isAgree && $saveData['user_info'] = $data['to_user_info'];
        $isAgree && $saveData['user_id'] = $data['to_user'];    
        $saveData['transfer_log'] = $transfers;
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res);
    }

    /*对方进行直接转让时，修改证书持有人信息等 $data: 转让记录表里的一条记录*/
    public function transferCertificateDirect($data): array 
    {

        $_where['status'] = 1;
        $_where['is_transfer'] = 0;
        $_where['id'] = $data['certificate_id'];
        $_where['user_id'] = $data['user_id'];
        $info = $this->model($this->certificateModel)->where($_where)->find();
        if(!$info){ return auto_failure(null, '未找到符合条件的证书信息'); }
        $info = $info->toArray();

        // 对data进行简化用户的信息
        $newTransLog = [];
        $newTransLog['user_id'] = $data['user_id'];
        $newTransLog['to_user'] = $data['to_user'];
        $newTransLog['status'] = $data['status'];
        $newTransLog['status_text'] = $data['status_text'];
        $newTransLog['create_time'] = $data['create_time'];
        $newTransLog['update_time'] = $data['update_time'];
        $newTransLog['user_info'] = ['name'=>$data['user_info']['name']];
        $newTransLog['to_user_info'] = ['name'=>$data['to_user_info']['name']];
        $newTransLog['certificate_price'] = $data['certificate_price'];
        $newTransLog['type'] = $data['type'];

        if(!$info['transfer_log']){
            $transfers = [];
            $transfers[] = $newTransLog;
        }else{
            array_push($info['transfer_log'], $newTransLog);  //将转让记录表的一条记录压到证书表里的转让记录字段中
            $transfers = $info['transfer_log'];
        }
        $saveData['user_id'] = $data['to_user'];    
        $saveData['transfer_log'] = $transfers;
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        return auto_return($res);
    }
    
    /*获取证书数量*/
    public function counts($data): array 
    {
        $_where['status'] = 1;
        if($data['type'] == 'all'){
            $count = $this->db()->field('count(*) as counts,type')->where($_where)->group('type')->select();
            $res = [];
            foreach ($count as $k => $v) {
                $res[$v['type'] . 'Certificate'] = $v['counts'];
            }
        }else{
            $res = $this->db()->where($_where)->count();
        }
        return auto_success($res, '成功获取证书数量');
    }

    /*前台获取证书列表*/
    public function allCertiList($map = []): array 
    {
        $map['status'] = 1;
        return $this->getCertiList($map);
    }
   
    /*内部获取证书列表*/
    public function getCertiList($data = []): array 
    {
        $data['price_start'] = $data['price_start'] ?? 0;
        $_idOrNameWhere = [];
        if(isset($data['keywords']) && $data['keywords']){ 
            if(is_numeric($data['keywords'])){
                $_where['c.id'] = $data['keywords'];
                $_idOrNameWhere['c.name'] =  ['like', '%' . (string) $data['keywords'] . '%'];
            }else{
                $_where['c.name|c.goods_info$.authors'] = ['like', '%' . (string) $data['keywords'] . '%'];
            }
        }
        if(isset($data['uid']) && $data['uid']){ 
            $_where['c.user_id'] = $data['uid'];
        }
        if(isset($data['cate_id']) && $data['cate_id']){
            $_where['c.goods_info$.search_fields$.cate_ids'] = ['like', '%' . $data['cate_id'] . '%'];
        }
        if(isset($data['no_distribute_date']) && $data['no_distribute_date']){
            $_where['c.last_integral_distribute_date'] = ['neq', $data['no_distribute_date']];
        }
        if(isset($data['price_start']) && isset($data['price_end']) && isset($data['symbol']) && in_array($data['symbol'], ['elt','between','egt'])){
            if(!$data['price_start'] && !$data['price_end']){ return verify_err(null, 'symbol存在时，请传入price_start或price_end'); }
            if($data['symbol'] == 'elt'){
                $_where['c.goods_info$.price'] = ['elt',$data['price_end']];
            }elseif($data['symbol'] == 'between'){
                $_where['c.goods_info$.price'] = ['between',[ $data['price_start'],$data['price_end'] ]];
            }else{
                $_where['c.goods_info$.price'] = ['egt',$data['price_start']];
            }
        }
        //对商品的可搜索字段进行搜索
        if(isset($data['search_fields']) && $data['search_fields']){
            foreach ($data['search_fields'] as $k => $v) {  // 例 search_fields:[{"en_name":"pattern","value":"古代"}]
                if(isset($v['en_name'],$v['value']) && $v['en_name'] && $v['value']){
                    $searchFields = 'c.goods_info$.search_fields.' . $v['en_name'];
                    $_where[$searchFields] = ['like','%,'.$v['value'].',%'];
                }
            }
        }
        if(isset($data['type']) && $data['type']){ $_where['c.type'] = $data['type']; }
        if(isset($data['is_pick']) && $data['is_pick'] !== ''){
            /*if($data['is_pick'] == 2){  //提货中
                $_where['pick_up_goods.pick_up_code'] = ['exp','is not null'];
                $_where['c.is_pick'] = 0;
            }else{
                $_where['c.is_pick'] = $data['is_pick'];  
            }*/
            $_where['c.is_pick'] = $data['is_pick'];  
        }
        if(isset($data['pick_up_code']) && $data['pick_up_code'] !== ''){ $_where['pick_up_goods.pick_up_code'] = $data['pick_up_code']; }
        if(isset($data['is_transfer']) && $data['is_transfer'] !== ''){ $_where['c.is_transfer'] = $data['is_transfer']; }
        if(isset($data['status']) && $data['status'] !== ''){ $_where['c.status'] = $data['status']; }
        if(isset($data['is_recommend']) && $data['is_recommend'] !== ''){ $_where['c.is_recommend'] = $data['is_recommend']; }
        if(isset($data['user_id'])){ $_where['c.user_id'] = $data['user_id']; }
        $res = $this->model($this->certificateModel)
                    ->alias('c')
                    ->field('c.id,c.app_id,c.other_app_read,c.is_public,c.name,c.product_code,c.user_id,c.goods_id,c.type,c.earnings,c.last_integral_distribute_date,c.is_pick,c.is_recommend,c.apply_invalid,c.is_transfer,c.status,c.create_time,c.update_time,c.goods_info,c.order_info,pick_up_code,transfer_status')
                    ->join('pick_up_goods', 'pick_up_goods.certificate_id = c.id', 'LEFT')
                    ->where($_where)
                    ->whereOr($_idOrNameWhere)
                    ->order('update_time', 'desc')
                    ->paginate(null,false,['page'=>$data['page'],'list_rows'=>$data['listRows']])
                    ->toArray();
        $res['certificate_ids'] = array_column($res['data'], "id");
        return auto_return_page($res);
    }

    /*根据商品id数组获取该商品所对应的证书状态*/
    public function getStatusByGoodsId($data): array 
    {
        $_where['status'] = ['neq',3];
        $_where['goods_id'] = ['in',$data['goods_ids']];
        $res = $this->model($this->certificateModel)
                    ->where($_where)
                    ->column('status','goods_id');
        foreach ($data['goods_ids'] as $k => $v) {
            !isset($res[$v]) && $res[$v] = -1;
        }
        return auto_return($res);
    }

    /*我的证书 - 确认提货*/
    //修改证书提货状态 + 修改证书提货单提货时间
    public function affirmPickUpGoods($data): array 
    {
        $_where['user_id'] = $data['user_id'];
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $_where['is_transfer'] = 0;
        $_where['is_pick'] = 0;
        $saveData['is_pick'] = 1;
        $res = $this->model($this->certificateModel)->save($saveData, $_where);
        if(!$res){
            return auto_failure(null, '确认提货失败');
        }
        $_pickWhere['user_id'] = $data['user_id'];
        $_pickWhere['certificate_id'] = $data['id'];
        $_pickWhere['status'] = 1;
        $pickData['pick_up_time'] = NOW;
        $addPickTime = $this->model($this->pickUpGoodsModel)->save($pickData, $_pickWhere);
        return auto_return($res);
    }

    /*给多个证书进行积分派发操作
        【自增证书累计收益+修改证书最后一次派发日期+添加一条证书派发记录】
    */
    public function integralDistribute($data): array 
    {
        //修改证书信息
        $updateCertiData = $updateOne = $addDisData = $addOne = [];
        foreach ($data['yes_integral_distribute_info'] as $k => $v) {
            $updateOne['id'] = $v['certificate_id'];
            $updateOne['earnings'] = ['exp', 'earnings+' . $v['integral']];
            $updateOne['last_integral_distribute_date'] = $data['distribute_date'];
            $updateCertiData[] = $updateOne;
            $addOne['system_user_id'] = $data['system_user_id'];
            $addOne['system_user_name'] = $data['system_user_name'];
            $addOne['certificate_user_id'] = $v['certificate_user_id'];
            $addOne['certificate_id'] = $v['certificate_id'];
            $addOne['certificate_name'] = $v['certificate_name'];
            $addOne['certificate_product_code'] = $v['certificate_product_code'];
            $addOne['integral'] = $v['integral'];
            $addOne['distribute_date'] = $data['distribute_date'];
            $addOne['distribute_date_time'] = strtotime($data['distribute_date']);
            $addOne['status'] = 1;
            $addOne['remark'] = $v['remark'];
            $addOne['rule_fund_type'] = $v['rule_fund_type'];
            $addOne['rule_fund'] = $v['rule_fund'];
            $addOne['rule_integral'] = $v['rule_integral'];
            $addDisData[] = $addOne;
        }
        foreach ($data['no_integral_distribute_info'] as $k => $v) {
            $updateOne['id'] = $v['certificate_id'];
            $updateOne['last_integral_distribute_date'] = $data['distribute_date'];
            $updateCertiData[] = $updateOne;
            $addOne['system_user_id'] = $data['system_user_id'];
            $addOne['system_user_name'] = $data['system_user_name'];
            $addOne['certificate_user_id'] = $v['certificate_user_id'];
            $addOne['certificate_id'] = $v['certificate_id'];
            $addOne['certificate_name'] = $v['certificate_name'];
            $addOne['certificate_product_code'] = $v['certificate_product_code'];
            $addOne['integral'] = $v['integral'];
            $addOne['distribute_date'] = $data['distribute_date'];
            $addOne['distribute_date_time'] = strtotime($data['distribute_date']);
            $addOne['status'] = 0;
            $addOne['remark'] = $v['remark'];
            $addOne['rule_fund_type'] = $v['rule_fund_type'];
            $addOne['rule_fund'] = $v['rule_fund'];
            $addOne['rule_integral'] = $v['rule_integral'];
            $addDisData[] = $addOne;
        }
        $updateRes = $this->model($this->certificateModel)->saveAll($updateCertiData);
        $addRes = $this->model($this->certificateIntegralDistributeModel)->saveAll($addDisData);
        if($updateRes && $addRes){
            return auto_success($data, '成功给证书派发积分');
        }else{
            return auto_failure($data, '给证书派发积分失败');
        }
    }
    /*后台根据证书ids获取证书列表信息（不分页）*/
    public function getCertiListByIds($data): array 
    {
        $_where['id'] = ['in', $data['certificate_ids']];
        if($data['type'] !== ''){ $_where['type'] = $data['type']; }
        if($data['is_pick'] !== ''){ $_where['is_pick'] = $data['is_pick']; }
        if($data['is_transfer'] !== ''){ $_where['is_transfer'] = $data['is_transfer']; }
        if($data['status'] !== ''){ $_where['status'] = $data['status']; }
        $list = $this->model($this->certificateModel)
                    ->field('goods_info,transfer_log', true)
                    ->where($_where)
                    ->select();
        return auto_return($list, '成功找到证书列表', '获取证书列表失败');
    }
    /*根据搜索条件获取派发记录列表（不分页）*/
    public function getCertificateDistributeList($data): array 
    {
        $data['certificate_ids'] !== '' && $_where['certificate_id'] = ['in', $data['certificate_ids']];
        $data['distribute_date'] !== '' && $_where['distribute_date'] = $data['distribute_date'];
        $list = $this->model($this->certificateIntegralDistributeModel)->where($_where)->select();
        return auto_return($list, '成功查询到派发记录列表');
    }
    /*获取积分派发记录*/
    public function getDistributePageList($data): array 
    {
        $data['certificate_id'] !== '' &&$_where['certificate_id'] = $data['certificate_id'];
        $data['status'] !== '' &&$_where['status'] = $data['status'];
        $data['distribute_date'] !== '' && $_where['distribute_date'] = $data['distribute_date'];
        $data['keywords'] !== '' && $_where['certificate_name|certificate_id|certificate_product_code'] = ['like', '%' . $data['keywords'] . '%'];
        !isset($_where) && $_where = true; 
        $list = $this->model($this->certificateIntegralDistributeModel)
                    ->where($_where)
                    ->order('update_time', 'desc')
                    ->paginate(null, false, ['page'=>$data['page'], 'listRows'=>$data['listRows']])
                    ->toArray();
        return auto_return_page($list);
    }
    /*后台管理员获取需要派发积分的证书分页列表*/
    public function getNeedDistributeList($data): array 
    {
        $_where['type'] = 'advanced';
        $_where['is_pick'] = 0;
        $_where['status'] = 1;
        $_where['finish_distribute_time'] = ['egt', NOW];
        $_where['user_id'] = ['gt', MAX_SYSTEM_ID];
        
        if($data['neq_distribute_time']){
            $neqDistributeTime = bcadd(strtotime($data['neq_distribute_time']), 86400);
            $_where['create_time'] = ['elt', $neqDistributeTime];
            $_where['last_integral_distribute_date'] = ['neq', $data['neq_distribute_time']];
        }

        $field = 'id,name,create_time,type,status,is_pick,is_transfer,is_recommend,apply_invalid';
        if(isset($data['cate_id']) && $data['cate_id']){
            $field = 'id,name,create_time,type,status,is_pick,is_transfer,is_recommend,apply_invalid,goods_info';
            $_where['goods_info$.search_fields$.cate_ids'] = ['like', '%' . $data['cate_id'] . '%'];
        }
        if(isset($data['keywords']) && $data['keywords']){ 
            $_where['name|id'] = ['like', '%' . (string) $data['keywords'] . '%'];
        }
        $res = $this->model($this->certificateModel)
                    ->field($field)
                    ->where($_where)
                    ->order('update_time', 'desc')
                    ->paginate(null,false,['page'=>$data['page'],'list_rows'=>$data['listRows']])
                    ->toArray();
        $res['certificate_ids'] = array_column($res['data'], "id");
        return auto_return_page($res);
    }
    /*获取最近一周的证书增量和证书总数*/
    public function certiIncreTendency($data): array 
    {
        $dbDateFormat = $data['dbDateFormat'];
        $Db = \think\Db::connect(config('db_config_certificate'));
        $weekSql = "select count(*) as counts, FROM_UNIXTIME(create_time, '$dbDateFormat') as create_time_date from tp_certificate where create_time > UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) group by create_time_date";
        $queryRes = $Db->query($weekSql);
        $weeks = week_key_array($data['dateFormat']);
        $delQueryRes = [];
        foreach ($queryRes as $k => $v) {
            $delQueryRes[$v['create_time_date']] = $v['counts'];
        }
        $weekIncre = array_merge($weeks, $delQueryRes);
        $newWeekIncre = [];
        foreach ($weekIncre as $k => $v) {
            $one['date'] = $k;
            $one['value'] = $v;
            $newWeekIncre[] = $one;
        }
        $res['weekIncre'] = $newWeekIncre;
        $res['total'] = $this->db()->count();
        return auto_return($res);
    }



}